/**
 * VillagerManager - 村民管理器
 * 负责村民的移动、行为和动画
 */

// 村民职业配置
const VILLAGER_JOBS = {
  farmer: {
    name: '农民',
    icon: '👨‍🌾',
    color: '#8BC34A',
    workBuilding: 'farm'
  },
  worker: {
    name: '工人',
    icon: '👷',
    color: '#795548',
    workBuilding: 'sawmill'
  },
  merchant: {
    name: '商人',
    icon: '🧑‍💼',
    color: '#9C27B0',
    workBuilding: 'market'
  },
  scholar: {
    name: '学者',
    icon: '👨‍🎓',
    color: '#2196F3',
    workBuilding: 'school'
  },
  idle: {
    name: '闲置',
    icon: '👤',
    color: '#9E9E9E',
    workBuilding: null
  }
}

class VillagerManager {
  constructor(ctx) {
    this.ctx = ctx
    this.villagers = []
  }

  /**
   * 渲染所有村民
   */
  render(villagers, buildings, timestamp) {
    // 更新村民状态
    villagers.forEach(villager => {
      this.updateVillager(villager, buildings, timestamp)
    })
    
    // 绘制村民
    villagers.forEach(villager => {
      this.drawVillager(villager, timestamp)
    })
  }

  /**
   * 更新村民状态
   */
  updateVillager(villager, buildings, timestamp) {
    // 初始化村民数据
    if (!villager.position) {
      villager.position = { x: 100, y: 100 }
    }
    if (!villager.target) {
      villager.target = { ...villager.position }
    }
    if (!villager.state) {
      villager.state = 'idle'
    }
    if (!villager.job) {
      villager.job = 'idle'
    }
    if (!villager.speed) {
      villager.speed = 1
    }
    
    // 根据状态更新行为
    switch (villager.state) {
      case 'walking':
        this.updateWalking(villager)
        break
      case 'working':
        this.updateWorking(villager, timestamp)
        break
      case 'resting':
        // 休息状态不移动
        break
      case 'idle':
        this.updateIdle(villager, buildings, timestamp)
        break
    }
  }

  /**
   * 更新行走状态
   */
  updateWalking(villager) {
    const dx = villager.target.x - villager.position.x
    const dy = villager.target.y - villager.position.y
    const distance = Math.sqrt(dx * dx + dy * dy)
    
    if (distance < villager.speed) {
      // 到达目标
      villager.position = { ...villager.target }
      villager.state = 'working'
    } else {
      // 继续移动
      villager.position.x += (dx / distance) * villager.speed
      villager.position.y += (dy / distance) * villager.speed
    }
  }

  /**
   * 更新工作状态
   */
  updateWorking(villager, timestamp) {
    // 工作一段时间后休息
    if (!villager.workStartTime) {
      villager.workStartTime = timestamp
    }
    
    const workDuration = timestamp - villager.workStartTime
    if (workDuration > 10000) { // 工作10秒
      villager.state = 'resting'
      villager.workStartTime = null
      villager.restStartTime = timestamp
    }
  }

  /**
   * 更新闲置状态
   */
  updateIdle(villager, buildings, timestamp) {
    // 寻找工作建筑
    const jobConfig = VILLAGER_JOBS[villager.job]
    if (!jobConfig || !jobConfig.workBuilding) return
    
    const workBuilding = buildings.find(b => b.id === jobConfig.workBuilding && b.built)
    if (workBuilding && workBuilding.position) {
      // 前往工作建筑
      villager.target = {
        x: workBuilding.position.x + 40,
        y: workBuilding.position.y + 40
      }
      villager.state = 'walking'
    }
  }

  /**
   * 绘制村民
   */
  drawVillager(villager, timestamp) {
    const { x, y } = villager.position
    const jobConfig = VILLAGER_JOBS[villager.job] || VILLAGER_JOBS.idle
    
    // 绘制阴影
    this.ctx.setFillStyle('rgba(0, 0, 0, 0.2)')
    this.ctx.beginPath()
    this.ctx.ellipse(x, y + 18, 12, 4, 0, 0, Math.PI * 2)
    this.ctx.fill()
    
    // 绘制村民身体
    this.ctx.setFillStyle(jobConfig.color)
    this.ctx.beginPath()
    this.ctx.arc(x, y, 12, 0, Math.PI * 2)
    this.ctx.fill()
    
    // 绘制村民图标
    this.ctx.setFontSize(16)
    this.ctx.setTextAlign('center')
    this.ctx.setTextBaseline('middle')
    this.ctx.fillText(jobConfig.icon, x, y)
    
    // 绘制行走动画（腿部）
    if (villager.state === 'walking') {
      const swing = Math.sin(timestamp / 200) * 5
      
      this.ctx.setStrokeStyle(jobConfig.color)
      this.ctx.setLineWidth(3)
      
      // 左腿
      this.ctx.beginPath()
      this.ctx.moveTo(x - 3, y + 12)
      this.ctx.lineTo(x - 5, y + 20 + swing)
      this.ctx.stroke()
      
      // 右腿
      this.ctx.beginPath()
      this.ctx.moveTo(x + 3, y + 12)
      this.ctx.lineTo(x + 5, y + 20 - swing)
      this.ctx.stroke()
    }
    
    // 绘制工作动画
    if (villager.state === 'working') {
      this.drawWorkingAnimation(villager, timestamp)
    }
    
    // 绘制状态图标
    this.drawStateIcon(villager, timestamp)
  }

  /**
   * 绘制工作动画
   */
  drawWorkingAnimation(villager, timestamp) {
    const { x, y } = villager.position
    const bounce = Math.sin(timestamp / 500) * 2
    
    // 工具图标
    const tools = {
      farmer: '🌾',
      worker: '⚒️',
      merchant: '💰',
      scholar: '📚'
    }
    
    const tool = tools[villager.job] || '⚒️'
    
    this.ctx.setFontSize(12)
    this.ctx.fillText(tool, x + 15, y - 10 + bounce)
  }

  /**
   * 绘制状态图标
   */
  drawStateIcon(villager, timestamp) {
    const { x, y } = villager.position
    let icon = ''
    
    // 根据状态显示图标
    if (villager.mood && villager.mood < 30) {
      icon = '😢'
    } else if (villager.energy && villager.energy < 20) {
      icon = '😴'
    } else if (villager.hunger && villager.hunger < 20) {
      icon = '🍽️'
    }
    
    if (icon) {
      // 图标闪烁效果
      const alpha = (Math.sin(timestamp / 500) + 1) / 2
      this.ctx.setGlobalAlpha(alpha)
      this.ctx.setFontSize(10)
      this.ctx.fillText(icon, x + 12, y - 15)
      this.ctx.setGlobalAlpha(1)
    }
  }

  /**
   * 点击检测
   */
  hitTest(x, y, villagers) {
    for (let i = villagers.length - 1; i >= 0; i--) {
      const villager = villagers[i]
      if (!villager.position) continue
      
      const dx = x - villager.position.x
      const dy = y - villager.position.y
      const distance = Math.sqrt(dx * dx + dy * dy)
      
      if (distance < 15) {
        const jobConfig = VILLAGER_JOBS[villager.job] || VILLAGER_JOBS.idle
        return {
          ...villager,
          jobName: jobConfig.name,
          jobIcon: jobConfig.icon
        }
      }
    }
    
    return null
  }

  /**
   * 添加新村民
   */
  addVillager(villager) {
    // 设置默认值
    if (!villager.position) {
      villager.position = { x: 100, y: 100 }
    }
    if (!villager.job) {
      villager.job = 'idle'
    }
    if (!villager.state) {
      villager.state = 'idle'
    }
    if (!villager.speed) {
      villager.speed = 1
    }
    if (!villager.mood) {
      villager.mood = 80
    }
    if (!villager.energy) {
      villager.energy = 60
    }
    
    this.villagers.push(villager)
    return villager
  }

  /**
   * 分配村民职业
   */
  assignJob(villager, job) {
    if (VILLAGER_JOBS[job]) {
      villager.job = job
      villager.state = 'idle' // 重新寻找工作
    }
  }
}

export default VillagerManager
export { VILLAGER_JOBS }
